package jgl.vajra.driver.part.web.activity;


import static jgl.vajra.driver.part.web.VersionComparator.compareVersionsWithDescription;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.ResolveInfo;
import android.graphics.Bitmap;
import android.location.Location;
import android.location.LocationManager;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.os.Message;
import android.os.Parcelable;
import android.os.StrictMode;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.text.format.DateFormat;
import android.util.Log;
import android.view.View;
import android.webkit.CookieManager;
import android.webkit.GeolocationPermissions;
import android.webkit.JavascriptInterface;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceError;
import android.webkit.WebResourceRequest;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.orhanobut.logger.Logger;

import java.io.File;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Comparator;
import java.util.List;
import java.util.Locale;

import jgl.vajra.driver.BuildConfig;
import jgl.vajra.driver.R;
import jgl.vajra.driver.databinding.ActivityBaseWebviewBinding;
import jgl.vajra.driver.part.web.UpdateDialog;
import jgl.vajra.driver.part.web.VersionUpdateBean;
import jgl.vajra.driver.part.web.viewmodel.BaseWebViewViewModel;
import jgl.vajra.driver.widget.bean.WebViewInfo;
import jgl.vajra.driver.widget.mvvm.factory.CreateViewModel;
import jgl.vajra.driver.widget.mvvm.view.BaseMVVMActivity;
import jgl.vajra.driver.widget.permissions.PermissionListener;
import jgl.vajra.driver.widget.permissions.PermissionsUtil;
import jgl.vajra.driver.widget.utils.ToastUtils;

/**
 * Created by Administrator on 2018/9/17.
 */
@CreateViewModel(BaseWebViewViewModel.class)
public class BaseWebViewActivity extends BaseMVVMActivity<BaseWebViewViewModel, ActivityBaseWebviewBinding> implements View.OnClickListener {

    private WebViewInfo webViewInfo;

    private ValueCallback<Uri> mUploadMessage;
    private ValueCallback<Uri[]> mUploadCallbackAboveL;
    private Uri imageUri; //图片地址


    private final static int GET_ADDRESS = 1;
    private String latAndLng = "";
    private AMapLocationClient mLocationClient;

    @Override
    public int getLayoutId() {
        return R.layout.activity_base_webview;
    }

    @Override
    protected boolean isNeedLoadStatusBar() {
        return false;
    }


    @SuppressLint("JavascriptInterface")
    @Override
    public void initView() {
        super.initView();
        webViewInfo = getIntent().getParcelableExtra("webInfo");

        //为了避免点击相册或者相机的按钮时报错
        StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
        StrictMode.setVmPolicy(builder.build());

        //GetVersionUpdate();
      /*  mBinding.webView.loadUrl(webViewInfo.url);

        mBinding.webView.setTvTitle(mBinding.toolbar.getTitleView());
        mBinding.webView.isUseWebViewTitle(TextUtils.isEmpty(webViewInfo.title));

        mBinding.webView.addJavascriptInterface(webViewJavascriptBridge, "appObject");*/


        WebSettings webSettings = mBinding.webView.getSettings();
        // 关键：添加 WebViewClient 拦截链接跳转
        mBinding.webView.setWebViewClient(new WebViewClient() {
            /**
             * 拦截所有链接跳转，强制在当前 WebView 内加载
             * @param view 当前 WebView
             * @param url 要跳转的链接
             * @return true：拦截跳转（自己处理）；false：不拦截（系统默认处理，可能打开浏览器）
             */
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {

                // 1. 过滤特殊协议（如电话、应用市场，避免 WebView 无法处理导致崩溃）
                if (url.startsWith("tel:") || url.startsWith("market:")) {
                    // 特殊协议交给系统处理（如 tel: 调用拨号界面）
                    Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
                    startActivity(intent);
                    return true; // 拦截该跳转，不进入 WebView
                }

                // 处理自定义URL Scheme
                try {
                    // 特殊处理腾讯地图
                    if (url.startsWith("qqmap://")) {
                        // 检查是否安装了腾讯地图
                        Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
                        List<ResolveInfo> activities = getPackageManager().queryIntentActivities(intent, 0);

                        if (!activities.isEmpty()) {
                            // 已安装腾讯地图，直接跳转
                            startActivity(intent);
                        } else {
                            // 未安装腾讯地图，提示用户
                            ToastUtils.showShort("未检测到腾讯地图，请先安装");
                            // 可选：跳转到应用商店下载
                            try {
                                startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=com.tencent.map")));
                            } catch (Exception e) {
                                // 应用商店不可用，跳转到网页版
                                mBinding.webView.loadUrl("https://map.qq.com/");
                            }
                        }
                        return true;
                    }
                } catch (Exception e) {
                    Log.e("URL_HANDLER", "处理URL失败", e);
                    ToastUtils.showShort("处理链接时发生错误");
                    return true;
                }

                try {
                    // 处理高德地图链接
                    if (url.startsWith("androidamap://") || url.startsWith("amapuri://")) {

                        // 创建Intent
                        Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
                        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP);
                        // 检查是否有应用可以处理该Intent
                        if (intent.resolveActivity(getPackageManager()) != null) {
                            startActivity(intent);
                            return true;
                        } else {
                            // 未安装高德地图，提示用户
                            ToastUtils.showShort("未检测到高德地图，请先安装");
                            // 可选：跳转到应用商店下载
                            // 未安装高德地图，跳转到应用商店
                            try {
                                startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=com.autonavi.minimap")));
                            } catch (Exception e) {
                                // 应用商店不可用，跳转到网页版
                                startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("https://uri.amap.com/")));
                            }
                        }
                        return true;
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    ToastUtils.showShort("无法打开地图应用");
                    return true;
                }

                try {
                    // 处理百度地图链接
                    if (url.startsWith("baidumap://")) {
                        // 创建Intent
                        Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
                        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP);

                        // 检查是否有应用可以处理该Intent
                        if (intent.resolveActivity(getPackageManager()) != null) {
                            // 已安装百度地图，直接跳转
                            startActivity(intent);
                        } else {
                            // 未安装百度地图，提示用户
                            ToastUtils.showShort("未检测到百度地图，请先安装");
                            // 跳转到应用商店下载
                            try {
                                startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=com.baidu.BaiduMap")));
                            } catch (Exception e) {
                                // 应用商店不可用，跳转到网页版
                                // 构建百度地图网页版URL，保留原始参数
                                String webUrl = convertBaiduMapUrlToWeb(url);
                                if (webUrl != null) {
                                    mBinding.webView.loadUrl(webUrl);
                                } else {
                                    // 默认打开百度地图首页
                                    mBinding.webView.loadUrl("https://map.baidu.com/");
                                }
                            }
                        }
                        return true;
                    }
                } catch (Exception e) {
                    e.printStackTrace();

                    ToastUtils.showShort("无法打开百度地图应用");
                    return true;
                }

                // 2. 普通 HTTP/HTTPS 链接，强制在当前 WebView 内加载
                view.loadUrl(url);
                return true; // 拦截跳转，自己处理
            }

            // 可选：添加页面加载状态监听（如加载失败、开始加载）
            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                super.onPageStarted(view, url, favicon);
                // 例如：显示加载进度条
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                // 例如：隐藏加载进度条
            }

            @Override
            public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
                super.onReceivedError(view, request, error);
                // 例如：加载失败时显示错误页面
            }
        });

        // 设置与Js交互的权限
        webSettings.setJavaScriptEnabled(true);
        webSettings.setDomStorageEnabled(true);

        // 设置允许JS弹窗
        webSettings.setJavaScriptCanOpenWindowsAutomatically(true);
        // 新增：禁止文件访问（避免本地链接误判）
        webSettings.setAllowFileAccess(false);
        webSettings.setAllowContentAccess(true);
        // 新增：禁止多窗口（避免触发外部浏览器新窗口）
        webSettings.setSupportMultipleWindows(false);

        // 通过addJavascriptInterface()将Java对象映射到JS对象
        //参数1：Javascript对象名
        //参数2：Java对象名
        mBinding.webView.addJavascriptInterface(new AndroidtoJs(), "jsInterface");//AndroidtoJS类对象映射到js的test对象

        // 先载入JS代码
        // 格式规定为:file:///android_asset/文件名.html
        //TODO 这个正式的
        mBinding.webView.loadUrl("https://www.aikazhinengkeji.com/login");//正式环境 洋洋的朋友
        //TODO 这个测试的
//        mBinding.webView.loadUrl("https://www.aikazhinengkeji.com:2033");//测试环境 洋洋的朋友

//        mBinding.webView.loadUrl("http://222.170.132.26:33001");//正式环境 洋洋的
//        mBinding.webView.loadUrl("http://test.lxspatial.com:49101 ");//测试环境
//        mBinding.webView.loadUrl("file:///android_asset/javascript.html");


        mBinding.webView.setWebChromeClient(new WebChromeClient() {
            //相机  相册
            @Override
            public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, FileChooserParams fileChooserParams) {
                mUploadCallbackAboveL = filePathCallback;
                takePhoto();
                return true;
            }

            // 拦截 JS 的 window.open() 多窗口请求
            @Override
            public boolean onCreateWindow(WebView view, boolean isDialog, boolean isUserGesture, Message resultMsg) {
                // 强制在当前 WebView 内加载新窗口链接
                WebView newWebView = new WebView(view.getContext());
                WebSettings settings = newWebView.getSettings();
                settings.setJavaScriptEnabled(true);
                // 将新窗口的 WebView 绑定到当前 WebView 的结果回调
                WebView.WebViewTransport transport = (WebView.WebViewTransport) resultMsg.obj;
                transport.setWebView(newWebView);
                resultMsg.sendToTarget();
                return true; // 拦截多窗口，自己处理
            }

            // 处理网页的地理位置权限请求
            @Override
            public void onGeolocationPermissionsShowPrompt(String origin, GeolocationPermissions.Callback callback) {
                // 允许指定网页（origin）获取地理位置权限
                callback.invoke(origin, true, false);
                // 第一个参数：网页源（origin）
                // 第二个参数：是否允许（true 为允许）
                // 第三个参数：是否记住该权限（false 为不记住，每次都询问；true 为记住，后续不再询问）
            }
        });
        AMapLocationClient.updatePrivacyShow(this, true, true);
        AMapLocationClient.updatePrivacyAgree(this, true);
        String[] strings = {
                Manifest.permission.ACCESS_FINE_LOCATION,
                Manifest.permission.ACCESS_COARSE_LOCATION,
                Manifest.permission.ACCESS_LOCATION_EXTRA_COMMANDS,
//                Manifest.permission.CALL_PHONE,
                Manifest.permission.WRITE_EXTERNAL_STORAGE,
                Manifest.permission.CAMERA};
        PermissionsUtil.requestPermission(this, new PermissionListener() {
                    @Override
                    public void permissionGranted(@NonNull String[] permissions) {
                        startLocation();
                    }

                    @Override
                    public void permissionDenied(@NonNull String[] permissions) {
                        ToastUtils.showShort("请到设置-权限管理中开启");
                    }
                }, strings
        );
//        getMyAddress();

    }

    private void GetVersionUpdate() {
       String  versionUpdate = "{\n" +
                "        \"apkUrl\": \"https://www.aikazhinengkeji.com/艾卡新能源-releaseProduct-V1.0.0.apk\",\n" +
                "        \"isUpdate\": true,\n" +
                "        \"version\": \"1.0.2\",\n" +
                "        \"versionInfo\": \"系统更新兑换及服务中心功能\"\n" +
                "    }";

        Logger.d("js调用Get_Version_Update" + versionUpdate);
        if (!TextUtils.isEmpty(versionUpdate)) {

            Gson gson = new Gson();
            Type type = new TypeToken<VersionUpdateBean>() {
            }.getType();
            VersionUpdateBean updateBean = gson.fromJson(versionUpdate, type);

            boolean result = compareVersionsWithDescription(updateBean.version, BuildConfig.VERSION_NAME);
            if (result) {
                List<String> list = new ArrayList<>();
                list.add(updateBean.versionInfo);

                UpdateDialog.DialogType force = updateBean.isUpdate ? UpdateDialog.DialogType.FORCE : UpdateDialog.DialogType.NORMAL;
                UpdateDialog.showUpdateDialog(getSupportFragmentManager(), BuildConfig.VERSION_NAME, updateBean.version,updateBean.apkUrl, list, force, new UpdateDialog.UpdateDialogListener() {
                    @Override
                    public void onUpdateNowClicked() {

                    }

                    @Override
                    public void onRemindLaterClicked() {

                    }

                    @Override
                    public void onSkipVersionClicked() {

                    }
                });
            }
        }
    }

    /**
     * 开始定位
     */
    public void startLocation() {
        //声明AMapLocationClient类对象
//            AMapLocationClient mLocationClient = null;
        try {
            mLocationClient = new AMapLocationClient(getApplicationContext());
            AMapLocationClientOption mLocationOption = new AMapLocationClientOption();
            mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);


            mLocationClient.setLocationListener(new AMapLocationListener() {
                @Override
                public void onLocationChanged(AMapLocation aMapLocation) {
                    if (aMapLocation != null) {
                        if (aMapLocation.getErrorCode() == 0) {//成功
                            //保存在本地
                            double lat = aMapLocation.getLatitude();
                            double lng = aMapLocation.getLongitude();
                            Logger.d("获取经纬度" + lat + "==========" + lng);
                            //获取到位置信息后的操作
                            latAndLng = lat + ":" + lng;
                        } else {//失败
                            Logger.d("定位失败 :" + aMapLocation.getErrorCode() + ", errInfo:" + aMapLocation.getErrorInfo());
                        }
                    }
                }
            });
            //获取一次定位结果：
            //该方法默认为false。
            //mLocationOption.setOnceLocation(true);//为true就不能连续定位
            mLocationOption.setInterval(30000);//设置间隔30秒
            mLocationClient.setLocationOption(mLocationOption);
//            mLocationClient.startLocation();

        } catch (Exception e) {
            throw new RuntimeException(e);
        }

    }


    private String getMyAddress() {
        //位置信息管理对象
        LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
        //获取内容提供者
        List<String> providers = locationManager.getProviders(true);
        Logger.d("providers: " + providers);
        if (providers.size() != 0) {
            //哪个位置提供者有位置信息，就用哪一个
            for (String provider : providers) {
                @SuppressLint("MissingPermission") Location location = locationManager.getLastKnownLocation(provider);
                if (location != null) {
                    Logger.d("location: " + location.getLatitude() + "==========" + location.getLongitude());

                    //获取到位置信息后的操作
                    return location.getLatitude() + ":" + location.getLongitude();
                }
            }
        } /*else {
            ToastUtils.showShort("没有位置信息内容提供者");
        }*/
        return "";
    }


    /**
     * 调用相机/相册选择窗
     */
    private void takePhoto() {
        String filePath = Environment.getExternalStorageDirectory() + File.separator;
//                + File.separator
//                + Environment.DIRECTORY_PICTURES + File.separator;
        String fileName = "IMG_" + DateFormat.format("yyyyMMdd_hhmmss", Calendar.getInstance(Locale.CHINA)) + ".jpg";
        imageUri = Uri.fromFile(new File(filePath + fileName));
        //相册相机选择窗
        Intent captureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        captureIntent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
        Intent Photo = new Intent(Intent.ACTION_PICK,
                MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        Intent chooserIntent = Intent.createChooser(Photo, "选择上传方式");
        chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, new Parcelable[]{captureIntent});
        startActivityForResult(chooserIntent, 1);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (Build.VERSION.SDK_INT >= 21) {
            chooseAbove(resultCode, data);
        } else {
            chooseBelow(resultCode, data);
        }
    }

    /**
     * Android API < 21(Android 5.0)版本的回调处理
     */
    public void chooseBelow(int resultCode, Intent data) {
        Log.e("Base", "调用方法  chooseBelow");
        if (Activity.RESULT_OK == resultCode) {
            updatePhotos();

            if (data != null) {
                // 这里是针对文件路径处理
                Uri uri = data.getData();
                if (uri != null) {
                    Log.e("Base", "系统里取到的图片：" + uri.toString());
                    mUploadMessage.onReceiveValue(uri);
                } else {
                    mUploadMessage.onReceiveValue(null);
                }
            } else {
                // 以指定图像存储路径的方式调起相机，成功后返回data为空
                Log.e("Base", "自己命名的图片：" + imageUri.toString());
                mUploadMessage.onReceiveValue(imageUri);
            }
        } else {
            mUploadMessage.onReceiveValue(null);
        }
        mUploadMessage = null;
    }

    /**
     * Android API >= 21(Android 5.0) 版本的回调处理
     */
    public void chooseAbove(int resultCode, Intent data) {
        Log.e("Base", "调用方法  chooseAbove   " + data);

        if (Activity.RESULT_OK == resultCode) {
            updatePhotos();

            if (data != null) {
                // 这里是针对从文件中选图片的处理
                Uri[] results;
                Uri uriData = data.getData();
                if (uriData != null) {
                    results = new Uri[]{uriData};
                    for (Uri uri : results) {
                        Log.e("Base", "系统里取到的图片：" + uri.toString());
                    }
                    mUploadCallbackAboveL.onReceiveValue(results);
                } else {
                    mUploadCallbackAboveL.onReceiveValue(null);
                }
            } else {
                Log.e("Base", "自己命名的图片：" + imageUri.toString());
                mUploadCallbackAboveL.onReceiveValue(new Uri[]{imageUri});
            }
        } else {
            mUploadCallbackAboveL.onReceiveValue(null);
        }
        mUploadCallbackAboveL = null;
    }

    //发送广播进行更新相册
    private void updatePhotos() {
        // 该广播即使多发（即选取照片成功时也发送）也没有关系，只是唤醒系统刷新媒体文件
        Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
        intent.setData(imageUri);
        sendBroadcast(intent);
    }

    @Override
    public void onBackPressed() {
        boolean isPress = backPress();
        Logger.d("backPress()" + isPress);
        if (!isPress)
            super.onBackPressed();
    }

    private boolean backPress() {
        if (mBinding.webView.canGoBack()) {
            mBinding.webView.goBack(); // goBack()表示返回WebView的上一页面
        }
        return mBinding.webView.canGoBack();
    }

    private void handlerCallBack() {
    }

    /**
     * 将百度地图的URL Scheme转换为网页版URL
     *
     * @param baiduMapUrl 百度地图的URL Scheme
     * @return 对应的网页版URL，如果无法转换则返回null
     */
    private String convertBaiduMapUrlToWeb(String baiduMapUrl) {
        try {
            Uri uri = Uri.parse(baiduMapUrl);
            String path = uri.getPath();

            // 根据不同的路径构建不同的网页URL
            if ("/map/marker".equals(path)) {
                // 处理标点功能
                String location = uri.getQueryParameter("location");
                String title = uri.getQueryParameter("title");
                String content = uri.getQueryParameter("content");

                if (location != null) {
                    StringBuilder webUrl = new StringBuilder("http://api.map.baidu.com/marker?");
                    webUrl.append("location=").append(location);
                    if (title != null) {
                        webUrl.append("&title=").append(Uri.encode(title));
                    }
                    if (content != null) {
                        webUrl.append("&content=").append(Uri.encode(content));
                    }
                    webUrl.append("&output=html&src=webapp.baidu.openAPIdemo");
                    return webUrl.toString();
                }
            } else if ("/map/geocoder".equals(path)) {
                // 处理地址解析
                String address = uri.getQueryParameter("address");
                if (address != null) {
                    return "http://api.map.baidu.com/geocoder?address=" +
                            Uri.encode(address) +
                            "&output=html&src=webapp.baidu.openAPIdemo";
                }
            } else if ("/map/direction".equals(path)) {
                // 处理路线规划
                String destination = uri.getQueryParameter("destination");
                String mode = uri.getQueryParameter("mode");

                if (destination != null) {
                    return "https://map.baidu.com/mobile/webapp/place/linesearch/foo=bar/from=place&" +
                            "end=" + Uri.encode(destination) +
                            (mode != null ? "&routeType=" + getRouteType(mode) : "");
                }
            }

            // 默认返回百度地图首页
            return "https://map.baidu.com/";
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 将百度地图的导航模式转换为网页版的路线类型
     *
     * @param mode 百度地图导航模式
     * @return 网页版路线类型
     */
    private String getRouteType(String mode) {
        switch (mode) {
            case "driving":
                return "2"; // 驾车
            case "transit":
                return "1"; // 公交
            case "walking":
                return "3"; // 步行
            case "riding":
                return "4"; // 骑行
            default:
                return "2"; // 默认驾车
        }
    }

    @Override
    public void onClick(View v) {
        onBackPressed();
    }

    @Override
    protected void onResume() {
        super.onResume();

        if (mLocationClient != null && !mLocationClient.isStarted())
            mLocationClient.startLocation();//开始定位
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (mLocationClient != null)
            mLocationClient.stopLocation();//停止定位后，本地定位服务并不会被销毁
    }

    @Override
    protected void onDestroy() {
        try {
            mBinding.webView.stopLoading();
            mBinding.webView.removeAllViewsInLayout();
            mBinding.webView.removeAllViews();
            //   CookieSyncManager.getInstance().stopSync();
            mBinding.webView.destroy();
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        } finally {
            super.onDestroy();
        }

        if (mLocationClient != null)
            mLocationClient.onDestroy();//销毁定位客户端，同时销毁本地定位服务。

    }

    public void clearCacheWebView() {
        //清除h5缓存
        if (mBinding.webView != null) {

            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    mBinding.webView.clearCache(true);

                    // 清除cookie即可彻底清除缓存
                    /*CookieSyncManager.createInstance(BaseWebViewActivity.this);
                    CookieManager.getInstance().removeAllCookie();*/

                    // 清除cookie即可彻底清除缓存
                    CookieManager.getInstance().removeAllCookies(null);
                    CookieManager.getInstance().flush();
                    // 刷新WebView
                    mBinding.webView.reload();
                }
            });
          /*  runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    mBinding.webView.clearCache(true);
                    // 清除磁盘缓存
                    clearDiskCache();
                    // 清除Cookie
                    CookieManager.getInstance().removeAllCookies(null);
                }
            });*/
        }
    }

    private void clearDiskCache() {
        try {
            File cacheDir = this.getCacheDir();
            if (cacheDir != null && cacheDir.exists() && cacheDir.isDirectory()) {
                deleteFiles(cacheDir);
            }
            if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
                File externalCacheDir = this.getExternalCacheDir();
                if (externalCacheDir != null && externalCacheDir.exists() && externalCacheDir.isDirectory()) {
                    deleteFiles(externalCacheDir);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void deleteFiles(File dir) {
        File[] files = dir.listFiles();
        if (files != null) {
            Arrays.sort(files, new Comparator<File>() {
                @Override
                public int compare(File f1, File f2) {
                    return Long.compare(f2.lastModified(), f1.lastModified());
                }
            });
            for (File file : files) {
                if (file.isDirectory()) {
                    deleteFiles(file);
                } else {
                    file.delete();
                }
            }
        }
    }

    // 继承自Object类
    public class AndroidtoJs extends Object {
        // 定义JS需要调用的方法
        // 被JS调用的方法必须加入@JavascriptInterface注解
        @JavascriptInterface
        public void Get_Clear(String msg) {
            Logger.d("js调用Android-Get_Clear" + msg);
            if (!TextUtils.isEmpty(msg))
                ToastUtils.showShort(msg);
            clearCacheWebView();
        }

        @JavascriptInterface
        public void Get_Phone(String phone) {
            Logger.d("js调用Android-Get_Phone" + phone);
            if (TextUtils.isEmpty(phone)) {
                ToastUtils.showShort("电话号码不能为空");
                return;
            }

            // 2. 根据号码拨打电话
            Intent intent = new Intent();        // 创建一个意图
            intent.setAction(Intent.ACTION_CALL);        // 指定其动作为拨打电话
            intent.setData(Uri.parse("tel:" + phone));    // 指定将要拨出的号码
            BaseWebViewActivity.this.startActivity(intent);    // 执行这个动作
        }

        @JavascriptInterface
        public String Get_longitude() {
            Logger.d("js调用Android-Get_longitude");
            return latAndLng;
           /* runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    String myAddress = getMyAddress();
                    mBinding.webView.loadUrl("javascript:toAndroidCallWithParam('" + myAddress + "')");
                }
            });*/
        }

        @JavascriptInterface
        public void Get_Version_Update(String versionUpdate) {
           /* versionUpdate = "{\n" +
                    "        \"apkUrl\": \"https://www.aikazhinengkeji.com/艾卡新能源-releaseProduct-V1.0.0.apk\",\n" +
                    "        \"isUpdate\": true,\n" +
                    "        \"version\": \"1.0.1\",\n" +
                    "        \"versionInfo\": \"系统更新兑换及服务中心功能\"\n" +
                    "    }";*/

            Logger.d("js调用Get_Version_Update" + versionUpdate);
            if (!TextUtils.isEmpty(versionUpdate)) {

                Gson gson = new Gson();
                Type type = new TypeToken<VersionUpdateBean>() {
                }.getType();
                VersionUpdateBean updateBean = gson.fromJson(versionUpdate, type);

                boolean result = compareVersionsWithDescription(updateBean.version, BuildConfig.VERSION_NAME);
                if (result) {
                    List<String> list = new ArrayList<>();
                    list.add(updateBean.versionInfo);

                    UpdateDialog.DialogType force = updateBean.isUpdate ? UpdateDialog.DialogType.FORCE : UpdateDialog.DialogType.NORMAL;
                    UpdateDialog.showUpdateDialog(getSupportFragmentManager(), BuildConfig.VERSION_NAME, updateBean.version,updateBean.apkUrl, list, force, new UpdateDialog.UpdateDialogListener() {
                        @Override
                        public void onUpdateNowClicked() {

                        }

                        @Override
                        public void onRemindLaterClicked() {

                        }

                        @Override
                        public void onSkipVersionClicked() {

                        }
                    });
                }
            }
        }
    }
}


